﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace ThreadingPrimeNumberSample
{
    public partial class PrimeCodeBehind : Window
    {
        public delegate void NextPrimeDelegate();

        private long _currentNumber = 3;
        private bool _continueCalculating;

        public PrimeCodeBehind()
            : base()
        {
            InitializeComponent();
        }

        private void StartOrStop(object sender, EventArgs e)
        {
            if (_continueCalculating)
            {
                _continueCalculating = false;
                startStopButton.Content = "Resume";
            }
            else
            {
                _continueCalculating = true;
                startStopButton.Content = "Stop";
                startStopButton.Dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    new NextPrimeDelegate(CheckNextNumber));
            }
        }

        public void CheckNextNumber()
        {
            // Reset flag.
            _isNotAPrime = false;

            for (long i = 3; i <= Math.Sqrt(_currentNumber); i++)
            {
                if (_currentNumber % i == 0)
                {
                    // Set not a prime flag to true.
                    _isNotAPrime = true;
                    break;
                }
            }

            // If a prime number.
            if (!_isNotAPrime)
            {
                bigPrime.Text = _currentNumber.ToString();
            }

            _currentNumber += 2;
            if (_continueCalculating)
            {
                startStopButton.Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.SystemIdle,
                    new NextPrimeDelegate(this.CheckNextNumber));
            }
        }

        private bool _isNotAPrime = false;
    }

}
